package com.samp.lang.classloader;

import java.io.File;

public class EncryptClassLoader extends ClassLoader {

    private static String des_key = "F85875C89D627354";

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        if( 2 > 1 ){
            System.out.println("findClass: " + name);
            String path = getClassRealPath(name);
            System.out.println("class path : "+path);
            try {
                byte[] data = EncryptClass.decrypt(path, des_key);

                Class<?> clz = defineClass(name, data, 0, data.length);
                return clz;
            }catch (Exception e){
                e.printStackTrace();
                throw new ClassNotFoundException("error",e);
            }
        }
        return super.findClass(name);
    }

    private  String getClassRealPath(String calssName){
        String[] prefix_path = {System.getProperty("user.dir"), "target","classes"};
        String[] paths = calssName.split("\\.");
        String[] real_path = new String[prefix_path.length+paths.length+1];
        System.arraycopy(prefix_path,0,real_path,0,prefix_path.length);
        System.arraycopy(paths,0,real_path,prefix_path.length,paths.length-1);
        real_path[real_path.length-2] ="encrypted";
        real_path[real_path.length-1] =paths[paths.length-1];
        return String.join(File.separator,real_path)+".class";
    }

    public static void main(String[] args) {
        EncryptClassLoader loader = new EncryptClassLoader();
        try {
            Class<?> clz = loader.loadClass("com.samp.lang.classloader.EncryptServiceImpl");
            System.out.println("loaded class:" + clz.getName() + " by " + clz.getClassLoader());
            EncryptService obj = (EncryptService) clz.newInstance();
            obj.test();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
